﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Specialized;

namespace WXY.Course.Common.MVCExtension
{
    internal abstract class UrlPager : Pager
    {
        protected RouteValueDictionary pageParas = new RouteValueDictionary();

        public UrlPager(HtmlHelper htmlHelper, PagerConfig pageConfig)
            : this(htmlHelper, pageConfig, null)
        {
            //FillPageParas(htmlHelper);
            //this.actionName = pageParas["action"].ToString();
            //this.controllerName = pageParas["controller"].ToString();
        }

        public UrlPager(HtmlHelper htmlHelper, PagerConfig pageConfig, object urlParam)
            : base(htmlHelper, pageConfig)
        {
            FillPageParas(htmlHelper);
            if (urlParam != null)
            {
                AddUrlParams(urlParam);
            }
            this.actionName = pageParas["action"].ToString();
            this.controllerName = pageParas["controller"].ToString();
        }

        //填充分页参数
        private void FillPageParas(HtmlHelper htmlHelper)
        {
            var routeValues = htmlHelper.ViewContext.RequestContext.RouteData.Values;
            UseRouteValuesToFill(routeValues);

            var requestParas = GetRequestParas();
            UseRequestParasToFill(requestParas);
        }

        //将路由数据添加进PageParas
        private void UseRouteValuesToFill(RouteValueDictionary routeValues)
        {
            pageParas["controller"] = routeValues["controller"];
            pageParas["action"] = routeValues["action"];
        }

        private NameValueCollection GetRequestParas()
        {
            var request = HttpContext.Current.Request;
            var requestParas = new NameValueCollection(request.QueryString);
            requestParas.Add(request.Form);
            return requestParas;
        }

        private void AddUrlParams(object sender)
        {
            var properties = sender.GetType().GetProperties();
            foreach (var item in properties)
            {
                if (!pageParas.ContainsKey(item.Name))
                    pageParas.Add(item.Name, item.GetValue(sender, null).ToString());
            }
        }

        //将查询参数添加进PageParas
        private void UseRequestParasToFill(NameValueCollection requestParas)
        {
            foreach (var key in requestParas.AllKeys)
            {
                pageParas[key] = requestParas[key];
            }
        }



        protected string GetUrl(int pageNumber)
        {
            return GetUrl(pageNumber.ToString());
        }

        protected string GetUrl(string input)
        {
            pageParas[pageField] = input;
            return urlHelper.Action(actionName, controllerName, pageParas);
        }
    }
}
